<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>系统设置</title>
    <link rel="stylesheet" href="/assets/libs/layui/css/layui.css" />
    <link rel="stylesheet" href="/css/admin.css" />
</head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<body class="layui-layout-body">

<div class="layui-container" style="padding: 20px; display: flex; justify-content: space-between;">
    <!-- 左侧设置框 -->
    <fieldset class="layui-elem-field" style="flex: 1; margin-right: 20px;">
        <legend>系统设置</legend>
        <div class="layui-field-box">
            <form class="layui-form" lay-filter="systemSettingsForm"
                  th:action="@{/templates/settings/settings/save}" method="post">
                <!-- 专家指导学生人数上限 -->
                <div class="layui-form-item">
                    <label class="layui-form-label">指导学生人数上限</label>
                    <div class="layui-input-block">
                        <input type="number" name="stu_max_num" placeholder="请输入上限人数" class="layui-input" required>
                    </div>
                </div>

                <!-- 学员考核成绩占比 -->
                <div class="layui-form-item">
                    <label class="layui-form-label">考勤占比</label>
                    <div class="layui-input-block">
                        <input type="number" name="attendance_rate" placeholder="请输入考勤占比（0-100）" class="layui-input" required>
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">作业占比</label>
                    <div class="layui-input-block">
                        <input type="number" name="homework_rate" placeholder="请输入作业占比（0-100）" class="layui-input" required>
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">日志占比</label>
                    <div class="layui-input-block">
                        <input type="number" name="log_rate" placeholder="请输入日志占比（0-100）" class="layui-input" required>
                    </div>
                </div>

                <!-- 提交按钮 -->
                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <button type="submit" class="layui-btn layui-btn-normal" style="background-color: #009688; border-color: #009688;" lay-submit lay-filter="saveSettings">保存设置</button>
                    </div>
                </div>
            </form>
        </div>
    </fieldset>

    <!-- 右侧饼图框 -->
    <fieldset class="layui-elem-field" style="flex: 1;">
        <legend>占比分析</legend>
        <div class="layui-field-box" style="text-align: center;">
            <div id="chart" style="width: 100%; height: 400px;"></div>
        </div>
    </fieldset>
</div>

<script src="/assets/libs/layui/layui.js"></script>
<script src="https://cdn.jsdelivr.net/npm/echarts/dist/echarts.min.js"></script>
<script>
    layui.use(['form'], function () {
        var form = layui.form;
        var $ = layui.jquery;

        // 初始化图表
        var chart = echarts.init(document.getElementById('chart'));
        var chartData = [
            {value: 40, name: '考勤'},
            {value: 30, name: '作业'},
            {value: 30, name: '日志'}
        ];
        var chartOption = {
            title: {
                text: '占比分析',
                left: 'center'
            },
            tooltip: {
                trigger: 'item'
            },
            legend: {
                orient: 'horizontal', // 设置图例为水平布局
                bottom: '0%', // 图例移动到饼图下方
                left: 'center', // 居中对齐
                data: ['考勤', '作业', '日志']
            },
            series: [
                {
                    name: '占比',
                    type: 'pie',
                    radius: '50%',
                    data: chartData,
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }
            ]
        };
        chart.setOption(chartOption);

        // 使用 AJAX 加载初始数据
        $.ajax({
            url: '/system/settings/data', // 后端接口 URL
            method: 'GET',               // 使用 GET 方法
            success: function (data) {
                // 确保返回的数据是 JSON 格式
                if (data) {
                    // 使用 layui 的 form.val 方法填充表单
                    form.val('systemSettingsForm', {
                        stu_max_num: data.stu_max_num,         // 注意 JSON 数据的键名
                        attendance_rate: data.attendance_rate,
                        homework_rate: data.homework_rate,
                        log_rate: data.log_rate,
                    });

                    // 更新饼图数据
                    chart.setOption({
                        series: [
                            {
                                data: [
                                    {value: data.attendance_rate, name: '考勤'},
                                    {value: data.homework_rate, name: '作业'},
                                    {value: data.log_rate, name: '日志'}
                                ]
                            }
                        ]
                    });
                } else {
                    console.error("后端返回数据为空！");
                }
            },
            error: function (xhr, status, error) {
                console.error("获取初始设置失败！", error);
            }
        });

        // 提交表单时的验证逻辑
        form.on('submit(saveSettings)', function (data) {
            // 获取表单中的占比数据
            var attendanceRate = parseFloat(data.field.attendance_rate) || 0;
            var homeworkRate = parseFloat(data.field.homework_rate) || 0;
            var logRate = parseFloat(data.field.log_rate) || 0;

            // 验证占比之和是否超过 100
            if ((attendanceRate + homeworkRate + logRate) != 100) {
                layer.msg('占比总和必须为 100，请调整！', {icon: 2}); // 提示错误
                return false; // 阻止表单提交
            }

            // 如果校验通过，执行 AJAX 请求
            $.ajax({
                url: '/system/settings/save',  // 确保此接口存在且正确配置
                method: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(data.field), // 将表单数据序列化为 JSON 字符串
                success: function (response) {
                    console.log(response); // 在控制台查看响应
                    layer.msg('设置保存成功！', {icon: 1});

                    // 更新饼图数据
                    chart.setOption({
                        series: [
                            {
                                data: [
                                    {value: attendanceRate, name: '考勤'},
                                    {value: homeworkRate, name: '作业'},
                                    {value: logRate, name: '日志'}
                                ]
                            }
                        ]
                    });
                },
                error: function (xhr, status, error) {
                    // 在控制台打印错误信息，便于调试
                    console.error("Error:", status, error);
                    layer.msg('保存失败，请重试！', {icon: 2});
                }
            });

            return false; // 防止表单默认提交
        });


    });

</script>

</body>
</html>
